package com.ibeetl.admin.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;


public class IPBaiduUtil {
	  /**
     * 此方法调用百度AIP来查询IP所在地域(YYR)
     * @param strIP（传入的IP地址）
     * @return
     */
    public static String getAddressByIPFromBaidu(String strIP) {
        try {
            URL url = new URL("http://api.map.baidu.com/location/ip?ak=F454f8a5efe5e577997931cc01de3974&ip="+strIP);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            String ipAddr = result.toString();
            System.out.println(ipAddr);
            try {
            	JSONObject jsonObject = new JSONObject(ipAddr);
            	
                if("0".equals(jsonObject.get("status").toString())){
                    JSONObject obj1= new JSONObject(jsonObject.get("content").toString());
                    JSONObject obj2= new JSONObject(obj1.get("address_detail").toString());
                    return obj2.get("city").toString();
                }else{
                    return "读取失败";
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return "读取失败";
            }

        } catch (IOException e) {
            return "读取失败";
        }
    }
    
    public static void main(String[] args) {
		System.out.println(getAddressByIPFromBaidu("202.102.152.3"));
	}
}
